﻿using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using iTeamyou.LTS.Core;
using iTeamyou.LTS.Core.Models;
using iTeamyou.LTS.Core.Services;
using Microsoft.Extensions.Hosting.WindowsServices;
using Microsoft.EntityFrameworkCore;
using BlazorDownloadFile;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.FileProviders;
using System.Net;
using iTeamyou.LTS.UI.Utils;
using Microsoft.AspNetCore.Rewrite;
using System.Runtime.InteropServices;

var options = new WebApplicationOptions
{
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService()
                                     ? AppContext.BaseDirectory : default
};

var builder = WebApplication.CreateBuilder(options);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddBootstrapBlazor();
builder.Services.AddScoped<DbContext, MainDBContext>()
    .AddScoped<DbContext, SSODBContext>()
    .AddScoped<SupplierService>()
    .AddScoped<SupplierAttachmentService>()
    .AddScoped<ProductService>()
    .AddScoped<ProductAttachmentService>()
    .AddScoped<ManufacturerService>()
    .AddScoped<ManufacturerAttachmentService>()
    .AddScoped<BatchService>()
    .AddScoped<BatchAttachmentService>()
    .AddScoped<SharedService>()
    .AddScoped<HttpContextAccessor>()
    .AddHttpContextAccessor();

builder.Services.AddDbContext<MainDBContext>(options => options.UseMySql(builder.Configuration.GetConnectionString("MainDB"), new MySqlServerVersion(new Version())))
    .AddDbContext<SSODBContext>(options => options.UseMySql(builder.Configuration.GetConnectionString("SSODB"), new MySqlServerVersion(new Version())));

builder.Services.AddTransient<IDataService<Supplier, SupplierLicense>, SupplierService>()
    .AddTransient<IDataService<Product, ProductLicense>, ProductService>()
    .AddTransient<IDataService<Manufacturer, ManufacturerLicense>, ManufacturerService>()
    .AddTransient<IDataService<Batch, BatchLicense>, BatchService>()
    .AddTransient<ILoginService<LoginUser>, SSOLoginService>()
    .AddTransient<IExcelHelper, NPOIHelper>();

builder.Services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true);
builder.Services.AddBlazorDownloadFile();

var sharedService = new SharedService();
//var isService = !(Debugger.IsAttached || args.Contains("--console"));
var isService = WindowsServiceHelpers.IsWindowsService();
if (isService)
{
    builder.Host.UseWindowsService();
}
var certFile = sharedService.GetConfig("CertFileName");
var certPassword = sharedService.GetConfig("CertPassword");

if (!builder.Environment.IsDevelopment())
{
    builder.WebHost.UseKestrel(options =>
    {
        options.Listen(IPAddress.Any, Int16.Parse(sharedService.GetConfig("Port")),
        listenOption =>
        {
            if (!string.IsNullOrWhiteSpace(certFile) && !string.IsNullOrWhiteSpace(certPassword))
                listenOption.UseHttps(certFile, certPassword);
        });
    });
}

var app = builder.Build();
var resourcePath = sharedService.GetConfig("ResourcePath");

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(resourcePath),
    RequestPath = new PathString("/files")
});

//var rwtopt = new RewriteOptions()
//             .AddRewrite("_blazor/(.*)", "lts/_blazor/$1", true);
//app.UseRewriter(rwtopt);
app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();

